import os
import pika
from dotenv import load_dotenv


class RabbitMQClient:
    def __init__(self):
        # 加载.env文件并初始化RabbitMQ连接参数
        load_dotenv()
        self.HOST = os.getenv('RABBIT_MQ_HOST')
        self.PORT = os.getenv('RABBIT_MQ_PORT')
        self.EXCHANGE_NAME = os.getenv('RABBIT_MQ_EXCHANGE_NAME')
        self.QUEUE_NAME = os.getenv('RABBIT_MQ_QUEUE_NAME')
        self.ROUTING_KEY = os.getenv('RABBIT_MQ_ROUTING_KEY')
        self.USERNAME = os.getenv('RABBIT_MQ_USERNAME')
        self.PASSWORD = os.getenv('RABBIT_MQ_PASSWORD')
        self.VIRTUAL_HOST = os.getenv('RABBIT_MQ_VIRTUAL_HOST')

        # 建立与RabbitMQ的连接
        self._connect()

    def _connect(self):
        """内部方法：建立与RabbitMQ的连接"""
        self.connection_params = pika.ConnectionParameters(
            host=self.HOST,
            port=self.PORT,
            virtual_host=self.VIRTUAL_HOST,
            credentials=pika.PlainCredentials(self.USERNAME, self.PASSWORD)
        )
        self.connection = pika.BlockingConnection(self.connection_params)
        self.channel = self.connection.channel()
        # 确保队列存在
        self.channel.queue_declare(queue=self.QUEUE_NAME)

    def send_message(self, message):
        """向RabbitMQ发送消息

        参数:
        - message: 要发送的消息内容 (str)
        """
        self.channel.basic_publish(
            exchange=self.EXCHANGE_NAME,
            routing_key=self.ROUTING_KEY,
            body=message
        )
        print(" [x] Sent '{}'".format(message))

    def close_connection(self):
        """关闭与RabbitMQ的连接"""
        self.connection.close()


# 使用示例
if __name__ == "__main__":
    client = RabbitMQClient()
    try:
        client.send_message('Hello World!')
    finally:
        client.close_connection()
